package nz.ac.massey.cs.pp.threading.randomprimes;

import java.util.List;

/**
 * This is the code executed in each thread.
 * @author jens dietrich
 */
public class GeneratePrimeNumbersWorker implements Runnable {

	private List<Integer> resultList = null; // results will be stored here
	private String name = null;
	
	public GeneratePrimeNumbersWorker(List<Integer> resultList,String name) {
		super();
		this.resultList = resultList;
		this.name = name;
	}

	@Override
	public void run() {
		long timeBefore = System.currentTimeMillis();
		while (resultList.size() < Settings.COUNT) {
			int nextRandom = RandomPrimeNumberGenerator.getNextRandomPrime(Settings.MAX_NUMBER);
			// an extra guard is needed here, because other threads could have already added 
			// enough numbers
			if (resultList.size() < Settings.COUNT) {
				resultList.add(nextRandom);
			}
		}
		long timeAfter = System.currentTimeMillis();
		System.out.println("Worker " + name + " finished, generated " + Settings.COUNT + " prime numbers, this took " + (timeAfter-timeBefore) + "ms");
		System.out.println("Result count is " + resultList.size());
	}

}
